import os
import datetime
from django.conf import settings
from .models import FileIndex

def rebuild_file_index():
    root = settings.FILE_ROOT
    FileIndex.objects.all().delete()
    count = 0
    for dirpath, dirnames, filenames in os.walk(root):
        rel_dir = os.path.relpath(dirpath, root)
        if rel_dir == '.':
            rel_dir = ''
        FileIndex.objects.create(
            path=rel_dir.replace('\\', '/'),
            name=os.path.basename(dirpath) or '/',
            size=0,
            mtime=datetime.datetime.fromtimestamp(os.path.getmtime(dirpath)),
            is_dir=True
        )
        count += 1
        for fname in filenames:
            fpath = os.path.join(dirpath, fname)
            rel_path = os.path.join(rel_dir, fname).replace('\\', '/')
            stat = os.stat(fpath)
            FileIndex.objects.create(
                path=rel_path,
                name=fname,
                size=stat.st_size,
                mtime=datetime.datetime.fromtimestamp(stat.st_mtime),
                is_dir=False
            )
            count += 1
    return count 